package cn.edu.lcu.cs.ssm.dao;

import java.sql.SQLException;
import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Repository;

import cn.edu.lcu.cs.ssm.entity.User;
import cn.edu.lcu.cs.ssm.mapper.UserMapper;
import cn.edu.lcu.cs.ssm.util.MyBatisUtil;

/**
 * <p>
 * 用MyBatis实现UserDao接口
 * </p>
 * <p>
 * 如果MyBatis与Spring集成，则用不到此实现类
 * </p>
 * 
 * @author Ling
 *
 */
// @Repository
public class UserDaoMybatisImpl implements UserDao {

	@Override
	public int update(User user) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public List<User> findAll() {
		// SqlSession的创建放在try-with-resources语句中，会被自动关闭
		try (SqlSession session = MyBatisUtil.getSession()) {
			UserMapper mapper = session.getMapper(UserMapper.class);
			List<User> users = mapper.findAll();
			// session.close(); // 让Session自动关闭
			return users;
		}
	}

	@Override
	public User findById(Long id) {
		try (SqlSession session = MyBatisUtil.getSession()) {
			UserMapper mapper = session.getMapper(UserMapper.class);
			return mapper.findById(id);
		}
	}

	@Override
	public User save(User user) {
		try (SqlSession session = MyBatisUtil.getSession()) {
			UserMapper mapper = session.getMapper(UserMapper.class);
			int count = mapper.save(user);
			session.commit();
			if (count == 0) {
				return null;
			} else {
				return user;
			}
		}
	}

	@Override
	public int delete(Long id) {
		try (SqlSession session = MyBatisUtil.getSession()) {
			UserMapper mapper = session.getMapper(UserMapper.class);
			int count = mapper.delete(id);
			session.commit();
			return count;
		}
	}

	@Override
	public long count() {
		try (SqlSession session = MyBatisUtil.getSession()) {
			UserMapper mapper = session.getMapper(UserMapper.class);
			return mapper.count();
		}
	}

	@Override
	public List<User> findByUsername(String username) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public User authenticate(String username, String password) {
		// TODO Auto-generated method stub
		return null;
	}

}
